package com.ztesoft.report.base.service.impl;


import com.baomidou.mybatisplus.entity.TableInfo;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
import com.ztesoft.report.base.dao.BaseMapper;
import com.ztesoft.report.base.service.BaseService;
import com.ztesoft.report.exception.RException;
import com.ztesoft.report.utils.seqcreate.IdGenerator;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author y3tu
 * @date 2018/1/29
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {

    @Override
    public Page<T> queryPage(Page<T> page, Map<String, Object> map) {
        return (Page<T>) baseMapper.queryPage(page,map);
    }

    @Override
    public boolean insert(T entity) {

        return retBool(baseMapper.insert(fillEntityId(entity)));
    }

    /**
     * 填充主键
     * @param entity
     * @author lei.zuman
     * @date 17/12/12
     */
    private T fillEntityId(T entity){
        if (null != entity) {
            Class<?> cls = entity.getClass();
            TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
            if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
                try {
                    Field f = cls.getDeclaredField(tableInfo.getKeyProperty());
                    f.setAccessible(true);
                    if (f.get(entity) == null) {
                        if (f.getType() == Integer.class) {
                            int id = IdGenerator.genIntValue(tableInfo.getTableName(), tableInfo.getKeyColumn());
                            f.set(entity, id);
                        } else if (f.getType() == Long.class) {
                            long id = IdGenerator.genLongValue(tableInfo.getTableName(), tableInfo.getKeyColumn());
                            f.set(entity, id);
                        } else if (f.getType() == String.class) {
                            long id = IdGenerator.genLongValue(tableInfo.getTableName(), tableInfo.getKeyColumn());
                            f.set(entity, String.valueOf(id));
                        } else {
                            throw new RException("主键类型不可用：" + f.getType().getName());
                        }
                    }
                } catch (NoSuchFieldException e) {
                    throw new RException("没有主键：" + tableInfo.getKeyProperty());
                } catch (IllegalAccessException e) {
                    throw new RException("主键不可访问：" + tableInfo.getKeyProperty());
                }
            }
        }
        return entity;
    }
}
